<template>
  <div class="departments-container">
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="dept-tree-container">
          <div class="tree-header">
            <h3>部门结构</h3>
            <div class="tree-actions">
              <el-button 
                size="small" 
                type="primary" 
                v-permission="'department:create'" 
                @click="handleAddDepartment"
              >
                添加
              </el-button>
              <el-button 
                size="small" 
                type="primary" 
                :disabled="!currentDept || !hasPermission('department:update')"
                @click="handleEditDepartment(currentDept)"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                :disabled="!currentDept || !hasPermission('department:delete')"
                @click="handleDeleteDepartment(currentDept)"
              >
                删除
              </el-button>
              <el-tooltip content="刷新部门树" placement="bottom">
                <el-button size="small" icon="Refresh" circle @click="refreshTree" />
              </el-tooltip>
            </div>
          </div>
          <div class="search-container">
            <el-input
              v-model="filterText"
              placeholder="输入关键字进行过滤"
              clearable
            />
          </div>
          <div class="tree-wrapper">
            <el-scrollbar always x-always>
              <div style="min-width: max-content; padding-bottom: 10px;">
                <el-tree
                  ref="deptTreeRef"
                  :data="departmentTree"
                  :props="defaultProps"
                  :filter-node-method="filterNode"
                  highlight-current
                  node-key="dept_id"
                  @node-click="handleNodeClick"
                  class="dept-tree"
                  :default-expand-level="1"
                  v-loading="treeLoading"
                >
                  <template #default="{ node, data }">
                    <span class="custom-tree-node">
                      <span>
                        <el-icon class="dept-folder-icon" :color="'#909399'">
                          <Folder v-if="!node.expanded" />
                          <FolderOpened v-else />
                        </el-icon>
                        <strong class="dept-name">{{ data.dept_name }}</strong>
                      </span>
                    </span>
                  </template>
                </el-tree>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="dept-content">
          <div class="content-header">
            <div class="header-info">
              <h3>{{ activeTab === 'users' ? '部门成员' : '部门权限' }}</h3>
              <el-tooltip v-if="currentDept" :content="currentDeptPath" placement="bottom" :show-after="500">
                <span class="selected-dept">当前: {{ currentDept.dept_name }}</span>
              </el-tooltip>
            </div>
            <div class="filter-actions">
              <el-button size="small" :type="activeTab === 'users' ? 'primary' : ''" icon="User" @click="activeTab = 'users'">用户</el-button>
              <el-button size="small" :type="activeTab === 'permissions' ? 'primary' : ''" icon="Key" @click="activeTab = 'permissions'">预览权限</el-button>
            </div>
          </div>

          <div class="tab-content">
            <!-- 用户列表 -->
            <div v-show="activeTab === 'users'" class="users-tab">
              <el-table
                v-loading="usersLoading"
                :data="usersList"
                border
                style="width: 100%"
                :max-height="550"
              >
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="username" label="用户名" />
                <el-table-column prop="name" label="姓名" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column label="角色">
                  <template #default="scope">
                    <div class="role-tags-wrapper">
                      <el-tag 
                        v-for="role in scope.row.roles" 
                        :key="role.id" 
                        class="role-tag"
                        type="info"
                      >
                        {{ role.name }}
                      </el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="状态">
                  <template #default="scope">
                    <el-tag :type="scope.row.status === '启用' ? 'success' : 'danger'">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="160" fixed="right">
                  <template #default="scope">
                    <el-button
                      size="small"
                      type="primary"
                      @click="handleEditUser(scope.row)"
                    >
                      编辑
                    </el-button>
                    <el-button
                      size="small"
                      type="danger"
                      @click="handleDeleteUser(scope.row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="userPagination.page"
                  v-model:page-size="userPagination.limit"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="userPagination.total"
                  @size-change="handleUserSizeChange"
                  @current-change="handleUserCurrentChange"
                />
              </div>
            </div>

            <!-- 部门权限管理 -->
            <div v-show="activeTab === 'permissions'" class="permissions-tab">
              <div class="permissions-header">
                <el-button 
                  v-if="currentDept"
                  type="primary" 
                  size="small" 
                  icon="Edit"
                  @click="handleManageDepartmentPermissions"
                >
                  管理权限
                </el-button>
              </div>

              <div v-if="!currentDept" class="empty-placeholder">
                <el-empty description="请先在左侧选择一个部门" />
              </div>
              
              <el-table
                v-else
                v-loading="permissionsLoading"
                :data="departmentPermissions"
                border
                style="width: 100%"
                :max-height="550"
              >
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="name" label="权限名称" />
                <el-table-column prop="code" label="权限代码" />
                <el-table-column prop="description" label="描述" />
              </el-table>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 部门表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加部门' : '编辑部门'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="deptFormRef"
        :model="deptForm"
        :rules="deptFormRules"
        label-width="80px"
      >
        <el-form-item label="部门名称" prop="dept_name">
          <el-input v-model="deptForm.dept_name" />
        </el-form-item>
        <el-form-item label="部门代码" prop="dept_id">
          <el-input v-model="deptForm.dept_id" :disabled="dialogType === 'edit'" />
          <span v-if="dialogType === 'edit'" style="color: #909399; font-size: 12px;">部门代码创建后不可修改</span>
        </el-form-item>
        <el-form-item label="上级部门" prop="parent_id">
          <div class="parent-dept-selector">
            <el-input 
              v-model="deptForm.parent_name" 
              placeholder="请选择上级部门" 
              readonly
              @click="showParentTree = true"
              suffix-icon="ArrowDown"
              class="parent-dept-input"
            >
              <template #append>
                <el-button 
                  v-if="deptForm.parent_id" 
                  @click.stop="clearParentSelection" 
                  icon="Close"
                />
              </template>
            </el-input>
            
            <div v-if="showParentTree" class="parent-tree-dropdown">
              <div class="tree-search">
                <el-input 
                  v-model="parentSearchText" 
                  placeholder="搜索部门" 
                  clearable
                  prefix-icon="Search"
                  @input="filterParentTree"
                />
              </div>
              <div class="parent-tree-container">
                <el-scrollbar height="250px" x-always>
                  <el-tree
                    ref="parentTreeRef"
                    :data="parentDeptTreeData"
                    :props="defaultProps"
                    :filter-node-method="filterParentNode"
                    node-key="dept_id"
                    highlight-current
                    :current-node-key="deptForm.parent_id"
                    @node-click="handleParentNodeClick"
                    :expand-on-click-node="false"
                    :check-strictly="true"
                  >
                    <template #default="{ node, data }">
                      <span class="compact-tree-node">
                        <span :class="{'selected-parent': deptForm.parent_id === data.dept_id}">
                          {{ data.dept_name }}
                        </span>
                      </span>
                    </template>
                  </el-tree>
                </el-scrollbar>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="order_num">
          <el-input-number v-model="deptForm.order_num" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="deptForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDeptForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 部门权限管理对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="部门权限设置"
      width="750px"
      destroy-on-close
      class="permission-management-dialog"
      top="2vh"
      :append-to-body="true"
      :close-on-click-modal="false"
      :fullscreen="false"
    >
      <div class="permission-dialog-content">
        <div class="dialog-header">
          <div class="dialog-subtitle">
            <el-icon><InfoFilled /></el-icon>
            当前管理部门: <strong>{{ currentDept?.dept_name }}</strong>
          </div>
        </div>
        
        <div class="permission-main">
          <div class="permission-content">
            <div class="content-header">
              <div class="search-box">
                <el-input
                  v-model="permissionSearchKeyword"
                  placeholder="搜索权限名称或代码..."
                  prefix-icon="Search"
                  clearable
                  @clear="handleClearPermissionSearch"
                  @input="handlePermissionSearch"
                />
              </div>
              
              <div class="permission-actions">
                <el-checkbox
                  v-model="selectAllPermissions"
                  @change="handleSelectAllPermissions"
                >
                  全选/取消全选
                </el-checkbox>
                <span class="permission-stats">已选 {{ selectedPermissions.length }} / {{ allPermissions.length }} 项</span>
              </div>
            </div>
            
            <div class="permissions-container" v-loading="loadingPermissions">
              <!-- 树形结构展示所有权限 -->
              <template v-if="!permissionSearchKeyword && allPermissions.length > 0">
                <el-scrollbar height="550px">
                  <div class="tree-container">
                    <el-tree
                      ref="permissionTreeRef"
                      :data="permissionTreeData"
                      :props="permissionTreeProps"
                      show-checkbox
                      node-key="id"
                      default-expand-all
                      :default-checked-keys="selectedPermissions"
                      @check="handlePermissionCheck"
                      class="permission-tree"
                    >
                      <template #default="{ node, data }">
                        <div class="tree-node-content">
                          <!-- 分类节点 -->
                          <template v-if="data.isCategory">
                            <el-icon class="category-icon"><Folder v-if="!node.expanded" /><FolderOpened v-else /></el-icon>
                            <span class="category-label">{{ data.name }}</span>
                            <span class="category-count">{{ data.children.length }}</span>
                          </template>
                          <!-- 权限节点 -->
                          <template v-else>
                            <span class="node-label">{{ data.name }}</span>
                            <span v-if="data.code" class="node-code">{{ data.code }}</span>
                            <el-tooltip
                              v-if="data.description"
                              :content="data.description"
                              placement="top"
                              :show-after="300"
                            >
                              <el-icon class="info-icon"><InfoFilled /></el-icon>
                            </el-tooltip>
                          </template>
                        </div>
                      </template>
                    </el-tree>
                  </div>
                </el-scrollbar>
              </template>
              
              <!-- 搜索结果 -->
              <template v-else-if="permissionSearchKeyword">
                <div class="search-results">
                  <p class="search-result-info">
                    搜索 "{{ permissionSearchKeyword }}" 的结果: {{ filteredPermissions.length }} 项
                  </p>
                  <el-scrollbar height="550px">
                    <div class="tree-container">
                      <el-tree
                        :data="searchTreeData"
                        :props="permissionTreeProps"
                        show-checkbox
                        node-key="id"
                        default-expand-all
                        :default-checked-keys="selectedPermissions"
                        @check="handlePermissionCheck"
                        class="permission-tree"
                      >
                        <template #default="{ node, data }">
                          <div class="tree-node-content">
                            <!-- 分类节点 -->
                            <template v-if="!data.code">
                              <el-icon class="category-icon"><Folder v-if="!node.expanded" /><FolderOpened v-else /></el-icon>
                              <span class="category-label">{{ data.name }}</span>
                              <span class="category-count">{{ data.children.length }}</span>
                            </template>
                            <!-- 权限节点 -->
                            <template v-else>
                              <span class="node-label">{{ data.name }}</span>
                              <span v-if="data.code" class="node-code">{{ data.code }}</span>
                              <el-tooltip
                                v-if="data.description"
                                :content="data.description"
                                placement="top"
                                :show-after="300"
                              >
                                <el-icon class="info-icon"><InfoFilled /></el-icon>
                              </el-tooltip>
                            </template>
                          </div>
                        </template>
                      </el-tree>
                    </div>
                  </el-scrollbar>
                </div>
              </template>
              
              <!-- 当没有权限时 -->
              <el-empty v-else-if="allPermissions.length === 0" description="无权限数据" />
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveDepartmentPermissions" :loading="savePermissionsLoading">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick, computed, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Folder, FolderOpened } from '@element-plus/icons-vue'
import { formatDateTime } from '../utils/format'
import { getDepartmentList, getDepartmentTree, createDepartment, updateDepartment, deleteDepartment, getDepartment, getDepartmentPermissions, setDepartmentPermissions, addDepartmentPermissions, removeDepartmentPermissions } from '../api/department'
import { getUserList } from '../api/user'
import { getPermissionList } from '../api/user'
import { useUserStore } from '../stores/user'

// 获取用户store
const userStore = useUserStore()

// 检查权限方法
const hasPermission = (permission) => {
  const hasPermissionResult = userStore.hasPermission(permission);
  console.log(`检查权限 ${permission}: ${hasPermissionResult ? '有权限' : '无权限'}`);
  return hasPermissionResult;
}

// 权限按钮禁用状态的计算属性
const isPermissionButtonDisabled = computed(() => {
  const noCurrentDept = !currentDept.value;
  
  // 尝试多种可能的权限命名
  const permissionOptions = [
    'department:permission:update',
    'department:permissions:update',
    'department:permission:manage',
    'department:permissions:manage',
    'department:permission',
    'department:permissions'
  ];
  
  // 检查是否有任一权限
  const hasAnyPermission = permissionOptions.some(perm => hasPermission(perm));
  const noPermission = !hasAnyPermission;
  
  const result = noCurrentDept || noPermission;
  
  console.log('权限按钮状态检查:', {
    当前部门: currentDept.value ? currentDept.value.dept_name : '未选择',
    部门级别: currentDept.value ? currentDept.value.level : 'N/A',
    权限检查结果: permissionOptions.map(perm => ({
      权限名: perm,
      是否有权限: hasPermission(perm)
    })),
    有任一权限: hasAnyPermission,
    按钮禁用: result
  });
  
  return false; // 临时返回false使按钮可点击，用于测试
})

// 当前选中部门的完整路径
const currentDeptPath = computed(() => {
  if (!currentDept.value) return '';
  
  // 获取完整路径
  const path = getDepartmentPath(currentDept.value.dept_id);
  return path || currentDept.value.dept_name;
})

// 表格数据
const departmentTree = ref([])
const usersList = ref([])
const departmentPermissions = ref([])
const usersLoading = ref(false)
const treeLoading = ref(false)
const permissionsLoading = ref(false)
const activeTab = ref('users')

// 当前选中的部门
const currentDept = ref(null)
const deptTreeRef = ref(null)

// 过滤树
const filterText = ref('')
const defaultProps = {
  children: 'children',
  label: 'dept_name'
}

// 级联选择器配置
// const departmentOptions = ref([])
// const cascaderProps = {
//   checkStrictly: true,
//   expandTrigger: 'hover',
//   value: 'dept_id',
//   label: 'dept_name',
//   emitPath: false,
//   children: 'children',
//   disabled: (data, node) => {
//     // 编辑模式下，不能选择自己或自己的子部门作为父部门
//     if (dialogType.value === 'edit' && deptForm.dept_id) {
//       if (data.dept_id === deptForm.dept_id) return true;
//       
//       // 检查是否是当前部门的子部门
//       if (data.children && data.children.length > 0) {
//         return checkIsChildDept(data.children, deptForm.dept_id);
//       }
//     }
//     return false;
//   }
// }

// 当前选择的父部门名称
// const selectedParentName = computed(() => {
//   if (!deptForm.parent_id) return '';
//   const parentDept = findDepartmentInTree(departmentTree.value, deptForm.parent_id);
//   return parentDept ? parentDept.dept_name : (deptForm.parent_name || '');
// })

// 扁平化部门选项，用于下拉选择
// const flattenDepartmentOptions = computed(() => {
//   const flatOptions = [];
//   const flatten = (departments, level = 0) => {
//     departments.forEach(dept => {
//       flatOptions.push({
//         ...dept,
//         level,
//         // 添加缩进前缀，表示层级关系
//         dept_name: '　'.repeat(level) + (level > 0 ? '└ ' : '') + dept.dept_name
//       });
//       
//       if (dept.children && dept.children.length > 0) {
//         flatten(dept.children, level + 1);
//       }
//     });
//   };
//   
//   flatten(departmentOptions.value);
//   return flatOptions;
// });

// 判断是否为子部门
const isChildDepartment = (dept, parentId) => {
  if (!dept || !parentId) return false;
  
  // 递归检查所有子部门
  const checkChildren = (childrenDepts, targetId) => {
    if (!childrenDepts || childrenDepts.length === 0) return false;
    
    for (const child of childrenDepts) {
      if (child.dept_id === targetId) return true;
      if (child.children && checkChildren(child.children, targetId)) return true;
    }
    
    return false;
  };
  
  return dept.children && checkChildren(dept.children, parentId);
}

// 分页
const userPagination = reactive({
  page: 1,
  limit: 10,
  total: 0
})

// 权限管理相关
const permissionDialogVisible = ref(false)
const permissionSearchKeyword = ref('')
const allPermissions = ref([])
const selectedPermissions = ref([])
const selectedPermissionIds = ref([])
const selectAllPermissions = ref(false)
const savePermissionsLoading = ref(false)
const loadingPermissions = ref(false)
const selectedCategory = ref('') // 当前选中的权限分类

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const deptFormRef = ref(null)
const deptForm = reactive({
  id: null,
  dept_name: '',
  dept_id: '',
  parent_id: null,
  parent_name: null,
  order_num: 0,
  description: ''
})

// 表单验证规则
const deptFormRules = {
  dept_name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  dept_id: [
    { required: true, message: '请输入部门代码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 监听过滤文本变化
watch(filterText, (val) => {
  deptTreeRef.value?.filter(val)
})

// 过滤节点方法
const filterNode = (value, data) => {
  if (!value) return true
  return data.dept_name.includes(value)
}

// 获取部门树
const fetchDepartmentTree = async () => {
  treeLoading.value = true;
  try {
    console.log('正在获取部门树...');
    const response = await getDepartmentTree();
    console.log('获取到的部门树响应:', response);
    
    if (response && response.data) {
      departmentTree.value = response.data.items || [];
      
      // 如果当前选中了部门，更新currentDept，因为树结构可能已经改变
      if (currentDept.value) {
        const updatedDept = findDepartmentInTree(departmentTree.value, currentDept.value.dept_id);
        if (updatedDept) {
          currentDept.value = updatedDept;
        }
      }
      
      // 生成级联选择器的选项
      if (dialogType.value === 'edit') {
        // departmentOptions.value = formatDeptOptions(response.data.items || []);
      }
    } else {
      console.error('获取部门树结构异常:', response);
      ElMessage.error('获取部门树失败: 返回结构异常');
    }
  } catch (error) {
    console.error('获取部门树失败:', error);
    ElMessage.error(error.response?.data?.detail || '获取部门树失败');
  } finally {
    treeLoading.value = false;
    
    // 确保树在数据加载后正确展开
    nextTick(() => {
      if (deptTreeRef.value) {
        // 手动展开根节点的所有子节点
        const rootNodes = departmentTree.value || [];
        rootNodes.forEach(rootNode => {
          if (rootNode.children && rootNode.children.length > 0) {
            deptTreeRef.value.store.nodesMap[rootNode.dept_id].expanded = true;
            // 展开第二级节点
            rootNode.children.forEach(childNode => {
              if (childNode.children && childNode.children.length > 0) {
                deptTreeRef.value.store.nodesMap[childNode.dept_id].expanded = true;
              }
            });
          }
        });
      }
    });
  }
}

// 在树中查找指定ID的部门
const findDepartmentInTree = (tree, departmentId) => {
  for (const dept of tree) {
    if (dept.dept_id === departmentId) {
      return dept;
    }
    if (dept.children && dept.children.length > 0) {
      const found = findDepartmentInTree(dept.children, departmentId);
      if (found) return found;
    }
  }
  return null;
}

// 获取用户的完整路径
const getDepartmentPath = (departmentId) => {
  // 存储路径的数组
  const path = [];
  
  // 递归查找部门路径
  const findPath = (tree, targetId, currentPath = []) => {
    for (const dept of tree) {
      // 创建当前路径的副本，并添加当前部门
      const newPath = [...currentPath, dept];
      
      // 如果找到目标部门，返回路径
      if (dept.dept_id === targetId) {
        return newPath;
      }
      
      // 如果有子部门，递归查找
      if (dept.children && dept.children.length > 0) {
        const foundPath = findPath(dept.children, targetId, newPath);
        if (foundPath) return foundPath;
      }
    }
    
    return null;
  };
  
  // 从部门树中查找路径
  const deptPath = findPath(departmentTree.value, departmentId);
  
  // 如果找到路径，格式化为字符串
  if (deptPath) {
    return deptPath.map(dept => dept.dept_name).join(' / ');
  }
  
  return null;
}

// 获取用户列表
const fetchUserList = async (departmentId = null) => {
  usersLoading.value = true
  try {
    const params = {
      page: userPagination.page,
      limit: userPagination.limit
    }
    
    if (departmentId) {
      params.department_id = departmentId
    }
    
    const response = await getUserList(params)
    if (response && response.data) {
      usersList.value = response.data.items
      userPagination.total = response.data.total
    }
    usersLoading.value = false
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    usersLoading.value = false
  }
}



// 获取部门权限列表
const fetchDepartmentPermissions = async (departmentId) => {
  permissionsLoading.value = true;
  try {
    const response = await getDepartmentPermissions(departmentId);
    if (response && response.data) {
      departmentPermissions.value = response.data || [];
    } else {
      departmentPermissions.value = [];
      ElMessage.error('获取部门权限失败');
    }
  } catch (error) {
    console.error('获取部门权限失败:', error);
    ElMessage.error(error.response?.data?.detail || '获取部门权限失败');
  } finally {
    permissionsLoading.value = false;
  }
};

// 管理部门权限
const handleManageDepartmentPermissions = async () => {
  console.log('==== 开始管理部门权限 ====');
  console.log('当前部门信息:', currentDept.value);
  
  if (!currentDept.value) {
    console.warn('没有选中的部门，无法管理权限');
    ElMessage.warning('请先选择一个部门');
    return;
  }
  
  // 清空搜索关键词
  permissionSearchKeyword.value = '';
  
  try {
    console.log(`正在为部门 [${currentDept.value.dept_name}] 加载权限数据...`);
    // 同时加载所有权限和部门当前权限
    loadingPermissions.value = true;
    selectedPermissions.value = [];
    
    const [allPermsResponse, deptPermsResponse] = await Promise.all([
      getPermissionList({ limit: 999 }),
      getDepartmentPermissions(currentDept.value.dept_id)
    ]);
    
    console.log('获取到的所有权限响应:', allPermsResponse);
    console.log('获取到的部门权限响应:', deptPermsResponse);
    
    // 处理所有权限数据
    if (allPermsResponse && allPermsResponse.data) {
      allPermissions.value = allPermsResponse.data.items || [];
      console.log(`成功加载 ${allPermissions.value.length} 个权限`);
    } else {
      allPermissions.value = [];
      console.error('获取权限列表失败，响应异常:', allPermsResponse);
      ElMessage.warning('获取权限列表失败');
    }
    
    // 处理部门当前权限
    if (deptPermsResponse && deptPermsResponse.data) {
      selectedPermissions.value = (deptPermsResponse.data || []).map(perm => perm.id);
      console.log(`部门已有 ${selectedPermissions.value.length} 个权限`);
    } else {
      selectedPermissions.value = [];
      console.error('获取部门权限失败，响应异常:', deptPermsResponse);
      ElMessage.warning('获取部门权限失败');
    }
    
    // 根据已选权限数量更新全选状态
    selectAllPermissions.value = 
      selectedPermissions.value.length > 0 && 
      selectedPermissions.value.length === allPermissions.value.length;
    
    console.log('权限数据加载完成，准备显示对话框');
    
  } catch (error) {
    console.error('初始化权限管理对话框失败:', error);
    console.error('错误详情:', error.response || error.message || error);
    ElMessage.error('加载权限数据失败');
    allPermissions.value = [];
    selectedPermissions.value = [];
  } finally {
    loadingPermissions.value = false;
    // 显示对话框
    permissionDialogVisible.value = true;
    console.log('权限管理对话框已显示');
  }
};

// 过滤权限列表
const filteredPermissions = computed(() => {
  if (!permissionSearchKeyword.value) {
    return allPermissions.value;
  }
  
  const keyword = permissionSearchKeyword.value.toLowerCase();
  return allPermissions.value.filter(
    perm => perm.name.toLowerCase().includes(keyword) || 
           perm.code.toLowerCase().includes(keyword) ||
           (perm.description && perm.description.toLowerCase().includes(keyword))
  );
});

// 过滤权限树节点
const filterPermissionNode = (value, data) => {
  if (!value) return true;
  
  // 如果是分类节点，则检查是否有匹配的子节点
  if (data.isCategory) {
    // 分类本身是否匹配
    if (data.name.toLowerCase().includes(value.toLowerCase())) {
      return true;
    }
    // 检查子节点是否有匹配
    return data.children && data.children.some(child => 
      child.name.toLowerCase().includes(value.toLowerCase()) ||
      (child.code && child.code.toLowerCase().includes(value.toLowerCase()))
    );
  }
  
  // 权限节点匹配
  return data.name.toLowerCase().includes(value.toLowerCase()) ||
         (data.code && data.code.toLowerCase().includes(value.toLowerCase()));
};

// 处理权限搜索
const handlePermissionSearch = () => {
  // 仅更新搜索关键字，搜索结果由计算属性处理
  console.log('搜索权限:', permissionSearchKeyword.value);
};

// 清除权限搜索
const handleClearPermissionSearch = () => {
  permissionSearchKeyword.value = '';
};

// 树形结构的权限配置
const permissionTreeRef = ref(null);
const permissionTreeProps = {
  children: 'children',
  label: 'name'
};

// 将权限转换为树形结构数据
const permissionTreeData = computed(() => {
  const categoryMap = {};
  
  // 根据权限代码的前缀进行分组
  allPermissions.value.forEach(permission => {
    // 提取权限代码的模块前缀（第一个冒号之前的部分）
    const category = permission.code.split(':')[0] || '其他';
    const categoryName = formatCategoryName(category);
    
    if (!categoryMap[category]) {
      categoryMap[category] = {
        id: `category_${category}`,
        name: categoryName,
        isCategory: true,
        children: []
      };
    }
    
    categoryMap[category].children.push({
      id: permission.id,
      name: permission.name,
      code: permission.code,
      description: permission.description,
      isCategory: false
    });
  });
  
  // 对每个分类下的权限进行排序
  Object.values(categoryMap).forEach(category => {
    category.children.sort((a, b) => a.name.localeCompare(b.name));
  });
  
  // 转换为数组并排序
  const sortedCategories = Object.values(categoryMap)
    .sort((a, b) => a.name.localeCompare(b.name));
    
  // 如果有分类但还未选择，默认选择第一个
  if (sortedCategories.length > 0 && !selectedCategory.value) {
    selectedCategory.value = sortedCategories[0].id;
  }
  
  return sortedCategories;
});

// 获取当前选中分类下的权限
// 当前选中分类的权限树数据
const currentCategoryTreeData = computed(() => {
  if (!selectedCategory.value || permissionSearchKeyword.value) {
    return [];
  }
  
  // 找到当前选中的分类
  const category = permissionTreeData.value.find(c => c.id === selectedCategory.value);
  if (!category) return [];
  
  // 直接返回当前分类的子权限
  return [{
    id: category.id,
    name: category.name,
    children: category.children,
    isCategory: true
  }];
});

// 搜索结果树形数据
const searchTreeData = computed(() => {
  if (!permissionSearchKeyword.value) {
    return [];
  }
  
  // 按权限代码的第一部分分组
  const groupedPermissions = {};
  
  filteredPermissions.value.forEach(permission => {
    const category = permission.code.split(':')[0] || '其他';
    const categoryName = formatCategoryName(category);
    
    if (!groupedPermissions[category]) {
      groupedPermissions[category] = {
        id: `search_category_${category}`,
        name: categoryName,
        children: []
      };
    }
    
    groupedPermissions[category].children.push({
      id: permission.id,
      name: permission.name,
      code: permission.code,
      description: permission.description
    });
  });
  
  // 返回搜索结果的树形结构
  return Object.values(groupedPermissions);
});

// 格式化分类名称，让它更易读
const formatCategoryName = (category) => {
  // 常见权限模块名称映射
  const categoryMap = {
    'user': '用户管理',
    'role': '角色管理',
    'permission': '权限管理',
    'department': '部门管理',
    'system': '系统管理',
    'workflow': '工作流管理',
    'task': '任务管理',
    'file': '文件管理',
    'report': '报表管理',
    'dashboard': '仪表盘',
    'api': 'API管理',
    'log': '日志管理',
    'notification': '消息通知',
    'audit': '审计',
    'other': '其他'
  };
  
  return categoryMap[category.toLowerCase()] || category.charAt(0).toUpperCase() + category.slice(1);
};

// 处理权限树节点选择
const handlePermissionCheck = (data, checked) => {
  // 获取当前树组件实例
  const treeComponent = permissionSearchKeyword.value ? 
    document.querySelector('.search-results .el-tree').__vueParentComponent.proxy : 
    permissionTreeRef.value;
  
  if (!treeComponent) {
    console.error('无法获取树组件实例');
    return;
  }
  
  // 获取所有选中的节点（不包括分类节点）
  const allCheckedNodes = treeComponent.getCheckedNodes().filter(node => !node.isCategory);
  const allCheckedKeys = allCheckedNodes.map(node => node.id);
  
  console.log('当前选中的权限:', allCheckedKeys);
  
  // 直接用树的选中状态更新selectedPermissions
  selectedPermissions.value = [...allCheckedKeys];
  
  // 更新全选状态
  selectAllPermissions.value = 
    selectedPermissions.value.length > 0 && 
    selectedPermissions.value.length === allPermissions.value.length;
};

// 保存部门权限
const saveDepartmentPermissions = async () => {
  try {
    savePermissionsLoading.value = true;
    console.log('保存部门权限 - 开始保存:', currentDept.value?.dept_id);
    
    if (!currentDept.value || !currentDept.value.dept_id) {
      ElMessage.error('无法保存权限：部门ID无效');
      return;
    }
    
    // 在保存前获取最新的选中状态
    let latestSelectedIds = [];
    
    // 根据当前激活的树获取选中的权限
    if (permissionSearchKeyword.value) {
      // 搜索模式下从搜索树获取
      const searchTree = document.querySelector('.search-results .el-tree').__vueParentComponent.proxy;
      if (searchTree) {
        const checkedNodes = searchTree.getCheckedNodes().filter(node => !node.isCategory);
        latestSelectedIds = checkedNodes.map(node => node.id);
      }
    } else {
      // 正常模式下从主树获取
      if (permissionTreeRef.value) {
        const checkedNodes = permissionTreeRef.value.getCheckedNodes().filter(node => !node.isCategory);
        latestSelectedIds = checkedNodes.map(node => node.id);
      }
    }
    
    console.log('最终提交的权限IDs:', latestSelectedIds);
    
    // 确保selectedPermissions与最新选中状态同步
    selectedPermissions.value = [...latestSelectedIds];
    
    // 获取变更前后的权限ID差异
    const currentPermissionIds = latestSelectedIds;
    const originalPermissionIds = departmentPermissions.value.map(p => p.id);
    
    console.log('原始权限IDs:', originalPermissionIds);
    console.log('新权限IDs:', currentPermissionIds);
    
    // 无论是否有变更，都进行保存以确保同步
    console.log('提交权限更新');
    const apiResponse = await setDepartmentPermissions(currentDept.value.dept_id, { 
      permission_ids: currentPermissionIds 
    });
    console.log('API响应:', apiResponse);
    
    ElMessage.success('部门权限设置成功');
    permissionDialogVisible.value = false;
    
    // 重新获取部门权限以更新显示
    await fetchDepartmentPermissions(currentDept.value.dept_id);
  } catch (error) {
    console.error('设置部门权限失败:', error);
    console.error('错误详情:', error.response?.data || error.message);
    ElMessage.error(error.response?.data?.detail || '设置部门权限失败');
  } finally {
    savePermissionsLoading.value = false;
  }
};

// 全选/取消全选
const handleSelectAllPermissions = (val) => {
  if (val) {
    // 全选所有权限
    selectedPermissions.value = allPermissions.value.map(p => p.id);
    
    // 更新当前激活的树
    if (permissionSearchKeyword.value) {
      // 搜索模式下更新搜索树
      const searchTree = document.querySelector('.search-results .el-tree')?.__vueParentComponent?.proxy;
      if (searchTree) {
        searchTree.setCheckedKeys(selectedPermissions.value);
      }
    } else {
      // 正常模式下更新主树
      if (permissionTreeRef.value) {
        permissionTreeRef.value.setCheckedKeys(selectedPermissions.value);
      }
    }
  } else {
    // 取消全选
    selectedPermissions.value = [];
    
    // 更新当前激活的树
    if (permissionSearchKeyword.value) {
      // 搜索模式下更新搜索树
      const searchTree = document.querySelector('.search-results .el-tree')?.__vueParentComponent?.proxy;
      if (searchTree) {
        searchTree.setCheckedKeys([]);
      }
    } else {
      // 正常模式下更新主树
      if (permissionTreeRef.value) {
        permissionTreeRef.value.setCheckedKeys([]);
      }
    }
  }
  
  console.log('全选/取消全选后的权限状态:', selectedPermissions.value);
}

// 选择/取消选择当前分类下的所有权限
const toggleCategoryPermissions = (categoryId, selected) => {
  const category = permissionTreeData.value.find(c => c.id === categoryId);
  if (!category) return;
  
  const permissionIds = category.children.map(p => p.id);
  
  if (selected) {
    // 添加该分类下所有未选中的权限
    permissionIds.forEach(id => {
      if (!selectedPermissions.value.includes(id)) {
        selectedPermissions.value.push(id);
      }
    });
  } else {
    // 移除该分类下所有权限
    selectedPermissions.value = selectedPermissions.value.filter(
      id => !permissionIds.includes(id)
    );
  }
  
  // 更新全选状态
  selectAllPermissions.value = 
    selectedPermissions.value.length > 0 && 
    selectedPermissions.value.length === allPermissions.value.length;
}

// 监听选中的权限变化，更新全选状态
watch(() => selectedPermissions.value, (newVal) => {
  selectAllPermissions.value = newVal.length === allPermissions.value.length && allPermissions.value.length > 0
}, { deep: true })

// 添加部门
const handleAddDepartment = () => {
  dialogType.value = 'add'
  resetDeptForm()
  
  // 如果当前有选中的部门，则设置为父部门
  if (currentDept.value) {
    deptForm.parent_id = currentDept.value.dept_id
    deptForm.parent_name = currentDept.value.dept_name
  }
  
  // 准备父部门树数据
  prepareParentDeptTree();
  
  dialogVisible.value = true;
  
  // 在树加载完成后设置当前选中节点
  nextTick(() => {
    if (parentTreeRef.value && deptForm.parent_id) {
      parentTreeRef.value.setCurrentKey(deptForm.parent_id);
    }
  });
}

// 编辑部门
const handleEditDepartment = async (dept) => {
  console.log('开始编辑部门:', dept);
  if (!dept) {
    console.error('无效的部门数据');
    return;
  }
  
  dialogType.value = 'edit';
  resetDeptForm();
  
  try {
    console.log('获取部门详情, dept_id:', dept.dept_id);
    const response = await getDepartment(dept.dept_id);
    console.log('部门详情响应:', response);
    
    if (response && response.data) {
      const deptData = response.data;
      
      deptForm.id = deptData.id;
      deptForm.dept_name = deptData.dept_name;
      deptForm.dept_id = deptData.dept_id;
      deptForm.parent_id = deptData.parent_id;
      deptForm.order_num = deptData.order_num || 0;
      deptForm.description = deptData.description || '';
      
      // 获取父部门的完整路径
      if (deptData.parent_id) {
        const parentPath = getDepartmentPath(deptData.parent_id);
        if (parentPath) {
          deptForm.parent_name = parentPath;
        } else {
          deptForm.parent_name = deptData.parent_name || '';
        }
      } else {
        deptForm.parent_name = '';
      }
      
      console.log('设置部门表单数据完成:', deptForm);
      
      // 准备父部门树数据
      prepareParentDeptTree();
      
      dialogVisible.value = true;
      
      // 在树加载完成后设置当前选中节点
      nextTick(() => {
        if (parentTreeRef.value && deptForm.parent_id) {
          parentTreeRef.value.setCurrentKey(deptForm.parent_id);
        }
      });
    } else {
      console.error('获取部门详情失败, 响应无数据');
      ElMessage.error('获取部门详情失败: 响应无数据');
    }
  } catch (error) {
    console.error('获取部门详情失败:', error);
    ElMessage.error(error.response?.data?.detail || '获取部门详情失败');
  }
}

// 重置部门表单
const resetDeptForm = () => {
  deptForm.id = null;
  deptForm.dept_name = '';
  deptForm.dept_id = '';
  deptForm.parent_id = null;
  deptForm.parent_name = null;
  deptForm.order_num = 0;
  deptForm.description = '';
}

// 提交部门表单
const submitDeptForm = async () => {
  if (!deptFormRef.value) return;
  
  await deptFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const formData = {
          dept_name: deptForm.dept_name,
          dept_id: deptForm.dept_id,
          parent_id: deptForm.parent_id,
          order_num: deptForm.order_num,
          description: deptForm.description
        };
        
        if (dialogType.value === 'add') {
          await createDepartment(formData);
          ElMessage.success('添加部门成功');
        } else {
          await updateDepartment(deptForm.dept_id, formData);
          ElMessage.success('更新部门成功');
        }
        
        dialogVisible.value = false;
        fetchDepartmentTree();
      } catch (error) {
        console.error('提交部门表单失败:', error);
        ElMessage.error(error.response?.data?.detail || '操作失败');
      }
    }
  });
}

// 删除部门
const handleDeleteDepartment = (dept) => {
  if (!dept) return;
  
  ElMessageBox.confirm(
    `确认删除部门 ${dept.dept_name} 吗？此操作将无法恢复！`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteDepartment(dept.dept_id);
      ElMessage.success('删除部门成功');
      fetchDepartmentTree();
      
      // 如果删除的是当前选中的部门，清除选择
      if (currentDept.value && currentDept.value.dept_id === dept.dept_id) {
        currentDept.value = null;
      }
    } catch (error) {
      console.error('删除部门失败:', error);
      ElMessage.error(error.response?.data?.detail || '删除部门失败');
    }
  }).catch(() => {
    // 取消删除
  });
}

// 权限管理相关
// 变量已在前面声明过，不再重复声明

// 页面加载逻辑已移至上方的onMounted中

// 监听标签切换
watch(activeTab, (val) => {
  if (val === 'users') {
    fetchUserList(currentDept.value?.dept_id)
  } else if (val === 'permissions') {
    fetchDepartmentPermissions(currentDept.value?.dept_id);
  }
})

// 获取有效的权限名称
const getValidPermissionName = () => {
  const permissionOptions = [
    'department:permission:update',
    'department:permissions:update',
    'department:permission:manage',
    'department:permissions:manage',
    'department:permission',
    'department:permissions'
  ];
  
  // 返回第一个有效的权限，如果都没有则返回第一个
  return permissionOptions.find(perm => hasPermission(perm)) || permissionOptions[0];
}

// 修复权限按钮方法
const fixPermissionButton = () => {
  console.log('尝试修复权限按钮...');
  // 检查所有可能的权限
  const validPermission = getValidPermissionName();
  const hasPermissionResult = hasPermission(validPermission);
  console.log(`检查权限 ${validPermission} 结果:`, hasPermissionResult);
  
  // 如果有权限但按钮仍然禁用，尝试强制刷新
  if (hasPermissionResult && currentDept.value) {
    console.log('条件满足但按钮仍禁用，尝试强制刷新...');
    // 强制刷新组件
    nextTick(() => {
      console.log('权限按钮应该可用状态：', !isPermissionButtonDisabled.value);
    });
  }
}

// 格式化部门选项，防止递归死循环
// const formatDeptOptions = (departments, parentId = null) => {
//   return departments.map(dept => {
//     // 当编辑部门时，避免自己成为自己的父部门
//     // 或者其下级部门成为其父部门
//     if (dialogType.value === 'edit' && deptForm.dept_id) {
//       // 如果是当前正在编辑的部门，跳过
//       if (dept.dept_id === deptForm.dept_id) {
//         return null;
//       }
//     }
//     
//     const formatted = {
//       dept_id: dept.dept_id,
//       dept_name: dept.dept_name,
//       parent_id: dept.parent_id,
//       isLeaf: !(dept.children && dept.children.length > 0)
//     }
//     
//     if (dept.children && dept.children.length > 0) {
//       const children = formatDeptOptions(dept.children, dept.dept_id)
//       if (children.length > 0) {
//         formatted.children = children.filter(Boolean)
//       }
//     }
//     
//     return formatted
//   }).filter(Boolean)
// }

// 检查是否为某部门的子部门
const checkIsChildDept = (children, deptId) => {
  for (const child of children) {
    if (child.dept_id === deptId) {
      return true;
    }
    if (child.children && child.children.length > 0) {
      const found = checkIsChildDept(child.children, deptId);
      if (found) return true;
    }
  }
  return false;
}

// 刷新部门树
const refreshTree = async () => {
  treeLoading.value = true;
  try {
    await fetchDepartmentTree();
    ElMessage.success('刷新成功');
    
    // 如果有当前选中的部门，重新定位
    if (currentDept.value && deptTreeRef.value) {
      nextTick(() => {
        // 尝试重新定位到当前选中的部门
        const node = deptTreeRef.value.getNode(currentDept.value.dept_id);
        if (node) {
          deptTreeRef.value.setCurrentKey(currentDept.value.dept_id);
        } else {
          // 如果找不到当前选中的部门，清空选中状态
          currentDept.value = null;
        }
      });
    }
  } finally {
    treeLoading.value = false;
  }
}

// 处理父部门选择变化
// const handleParentChange = (value) => {
//   // 如果清空了选择，也清空parent_name
//   if (!value) {
//     deptForm.parent_name = '';
//     return;
//   }
//   
//   // 查找选中的部门，更新parent_name
//   const selectedParent = findDepartmentInTree(departmentTree.value, value);
//   if (selectedParent) {
//     deptForm.parent_name = selectedParent.dept_name;
//     console.log('父部门变更为:', selectedParent.dept_name);
//   } else {
//     console.warn('未找到父部门信息:', value);
//   }
// }

// 点击树节点
const handleNodeClick = (data, node) => {
  console.log('树节点点击:', data, node);
  
  try {
    // 确保点击的节点数据完整
    if (!data || !data.dept_id) {
      console.error('无效的部门节点数据');
      return;
    }
    
    // 深拷贝数据，避免引用问题
    currentDept.value = JSON.parse(JSON.stringify(data));
    
    // 保存节点的level属性，用于控制按钮禁用状态
    currentDept.value.level = node.level;
    console.log('设置当前部门:', currentDept.value);
    console.log('当前部门层级:', node.level);
    
    // 获取并记录完整的部门路径
    const fullPath = getDepartmentPath(data.dept_id);
    console.log('当前部门完整路径:', fullPath);
    
    // 节点点击后，检查权限按钮状态
    nextTick(() => {
      fixPermissionButton();
      console.log('节点点击后权限按钮状态:', {
        isDisabled: isPermissionButtonDisabled.value,
        当前部门: currentDept.value.dept_name,
        当前部门路径: currentDeptPath.value,
        hasPermission: hasPermission('department:permission:update')
      });
    });
    
    if (activeTab.value === 'users') {
      userPagination.page = 1;
      fetchUserList(data.dept_id);
    } else if (activeTab.value === 'permissions') {
      fetchDepartmentPermissions(data.dept_id);
    }
  } catch (error) {
    console.error('处理节点点击时出错:', error);
    ElMessage.error('处理部门节点数据时出错');
  }
}



// 编辑用户
const handleEditUser = (user) => {
  console.log('编辑用户:', user);
  ElMessage.info('用户编辑功能待实现');
  // 这里可以实现打开编辑用户对话框的逻辑
}

// 删除用户
const handleDeleteUser = (user) => {
  console.log('删除用户:', user);
  ElMessageBox.confirm(
    `确认删除用户 ${user.username} 吗？此操作将无法恢复！`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 这里可以实现删除用户的API调用
      // await deleteUser(user.id);
      ElMessage.success('删除用户成功');
      // 重新获取用户列表
      fetchUserList(currentDept.value?.dept_id);
    } catch (error) {
      console.error('删除用户失败:', error);
      ElMessage.error(error.response?.data?.detail || '删除用户失败');
    }
  }).catch(() => {
    // 取消删除
  });
}

// 分页事件处理
const handleUserSizeChange = (val) => {
  userPagination.limit = val
  fetchUserList(currentDept.value?.dept_id)
}

const handleUserCurrentChange = (val) => {
  userPagination.page = val
  fetchUserList(currentDept.value?.dept_id)
}



// 变量定义部分
const parentSearchText = ref('')
const parentTreeRef = ref(null)
const parentDeptTreeData = ref([])

// 过滤父部门树节点
const filterParentNode = (value, data) => {
  if (!value) return true
  return data.dept_name.toLowerCase().includes(value.toLowerCase())
}

// 过滤父部门树
const filterParentTree = (val) => {
  parentTreeRef.value?.filter(val)
}

// 点击父部门树节点
const handleParentNodeClick = (data) => {
  // 编辑模式下，不能选择自己或自己的子部门作为父部门
  if (dialogType.value === 'edit' && deptForm.dept_id) {
    if (data.dept_id === deptForm.dept_id) {
      ElMessage.warning('不能选择自己作为父部门')
      return
    }
    
    // 检查是否是当前部门的子部门
    if (isChildDepartment(currentDept.value, data.dept_id)) {
      ElMessage.warning('不能选择自己的子部门作为父部门')
      return
    }
  }
  
  deptForm.parent_id = data.dept_id
  
  // 获取完整的部门路径
  const fullPath = getDepartmentPath(data.dept_id)
  if (fullPath) {
    deptForm.parent_name = fullPath
  } else {
    deptForm.parent_name = data.dept_name
  }
  
  showParentTree.value = false
}

// 清除父部门选择
const clearParentSelection = (event) => {
  if (event) {
    event.stopPropagation()
  }
  deptForm.parent_id = null
  deptForm.parent_name = null
  if (parentTreeRef.value) {
    parentTreeRef.value.setCurrentKey(null)
  }
}

// 准备父部门树数据
const prepareParentDeptTree = () => {
  // 深拷贝部门树数据
  const treeCopy = JSON.parse(JSON.stringify(departmentTree.value));
  
  // 编辑模式下，过滤掉自己和子部门
  if (dialogType.value === 'edit' && deptForm.dept_id) {
    const filterSelfAndChildren = (departments) => {
      return departments.filter(dept => {
        if (dept.dept_id === deptForm.dept_id) {
          return false;
        }
        
        if (dept.children && dept.children.length > 0) {
          dept.children = filterSelfAndChildren(dept.children);
        }
        
        return true;
      });
    };
    
    parentDeptTreeData.value = filterSelfAndChildren(treeCopy);
  } else {
    parentDeptTreeData.value = treeCopy;
  }
}

const showParentTree = ref(false)

// 监听点击事件，点击外部关闭树形选择器
const handleClickOutside = (event) => {
  if (showParentTree.value) {
    const parentSelector = document.querySelector('.parent-dept-selector')
    if (parentSelector && !parentSelector.contains(event.target)) {
      showParentTree.value = false
    }
  }
}

// 监听页面点击事件
onMounted(async () => {
  document.addEventListener('click', handleClickOutside)
  
  // 页面初始化逻辑
  console.log('页面加载，开始初始化...');
  
  // 首先确保用户权限已加载
  if (userStore.permissions.length === 0) {
    console.log('未检测到权限，尝试重新加载用户信息');
    await userStore.fetchUserInfo();
  }
  
  console.log('当前用户拥有的权限:', userStore.permissions);
  console.log('是否有部门权限管理权限:', hasPermission('department:permission:update'));
  
  // 获取部门树数据
  await fetchDepartmentTree();
  
  // 获取用户数据
  fetchUserList();
  
  console.log('页面初始化完成');
})

// 组件卸载前移除事件监听
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped lang="scss">
.departments-container {
  padding: 20px;
  
  .dept-tree-container {
    height: 650px;
    border-right: 1px solid #ebeef5;
    background-color: #fff;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    
    .tree-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #ebeef5;
      
      h3 {
        margin: 0;
        font-size: 16px;
        white-space: nowrap;
      }
      
      .tree-actions {
        display: flex;
        gap: 4px;
        flex-wrap: nowrap;
        margin-left: 10px;
      }
    }
    
    .search-container {
      margin-bottom: 20px;
      padding: 0 5px;
    }
    
    .tree-wrapper {
      height: calc(100% - 130px);
      overflow: hidden;
      margin-top: 15px;
      
      :deep(.el-scrollbar) {
        height: 100%;
        
        .el-scrollbar__wrap {
          overflow-x: scroll !important;
        }
        
        .el-scrollbar__bar.is-horizontal {
          display: block !important;
          height: 6px;
        }
        
        .el-tree {
          min-width: 100%;
          
          .el-tree-node__content {
            min-width: fit-content;
          }
        }
      }
      
      .dept-tree {
        width: 100%;
      }
    }
  }
  
  .dept-content {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    height: 650px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    
    .content-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .header-info {
        display: flex;
        flex-direction: column;
        
        h3 {
          margin: 0 0 5px 0;
        }
        
        .selected-dept {
          font-size: 12px;
          color: #909399;
          max-width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          padding: 2px 0;
          display: inline-block;
        }
      }
      
      .filter-actions {
        display: flex;
        gap: 8px;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .role-tags-wrapper {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
  }
  
  .permission-tag-container {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
  }
  
  .permissions-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .header-title {
      display: flex;
      align-items: center;
      gap: 5px;
      
      h4 {
        margin: 0;
      }
    }
  }
  
  .empty-placeholder {
    padding: 60px 0;
    text-align: center;
  }

  .custom-tree-node {
    display: flex;
    align-items: center;
    min-width: max-content;
    padding-right: 20px;
    
    .dept-folder-icon {
      margin-right: 5px;
      flex-shrink: 0;
    }
    
    .dept-name {
      line-height: 1.5;
      white-space: nowrap;
      overflow: visible;
    }
  }
}

.parent-dept-selector {
  position: relative;
  width: 100%;
  
  .el-input {
    width: 100%;
  }
  
  .parent-dept-input {
    :deep(.el-input__inner) {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 14px;
      color: #606266;
      cursor: pointer;
    }
  }
  
  .parent-tree-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background-color: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    z-index: 100;
    margin-top: 5px;
    width: 100%;
    
    .tree-search {
      padding: 8px;
      border-bottom: 1px solid #ebeef5;
      background-color: #f5f7fa;
    }
    
    .parent-tree-container {
      background-color: #fff;
      
      :deep(.el-tree) {
        padding: 5px;
        min-width: 100%;
        
        .el-tree-node__content {
          height: 32px; /* Slightly taller for better readability */
          padding-left: 8px !important;
          min-width: max-content;
          
          &:hover {
            background-color: #f5f7fa;
          }
        }
        
        .is-current > .el-tree-node__content {
          background-color: #ecf5ff;
          color: #409EFF;
        }
        
        /* Reduce spacing between nodes */
        .el-tree-node {
          padding-bottom: 0;
          white-space: nowrap;
          overflow: visible;
          min-width: max-content;
        }
        
        /* Adjust the expand arrow position */
        .el-tree-node__expand-icon {
          padding: 8px;
        }
        
        /* Adjust indentation for better hierarchy visualization */
        .el-tree-node__children {
          padding-left: 16px;
        }
      }
      
      :deep(.el-scrollbar__wrap) {
        overflow-x: auto;
      }
      
      .selected-parent {
        color: #409EFF;
        font-weight: 500;
      }
      
      .compact-tree-node {
        display: flex;
        align-items: center;
        font-size: 14px;
        line-height: 1.5;
        padding: 4px 0;
        white-space: nowrap;
      }
    }
  }
}

// 权限管理对话框样式
.permission-dialog-content {
  padding: 0;
  max-height: calc(96vh - 120px);
  overflow: hidden;
  
  .dialog-header {
    background-color: #f5f7fa;
    padding: 12px 15px;
    border-bottom: 1px solid #e4e7ed;
    margin-bottom: 5px;
    
    .dialog-subtitle {
      display: flex;
      align-items: center;
      color: #606266;
      font-size: 14px;
      
      .el-icon {
        margin-right: 8px;
        font-size: 14px;
        color: #909399;
      }
    }
  }
  
  .permission-main {
    height: 680px;
    max-height: calc(96vh - 160px);
    
    .permission-content {
      display: flex;
      flex-direction: column;
      height: 100%;
      
      .content-header {
        padding: 12px 15px;
        border-bottom: 1px solid #e4e7ed;
        
        .search-box {
          margin-bottom: 12px;
        }
        
        .permission-actions {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .permission-stats {
            font-size: 13px;
            color: #909399;
          }
        }
      }
      
      .permissions-container {
        flex: 1;
        padding: 15px;
        overflow: hidden;
        
        .search-result-info {
          margin-bottom: 15px;
          font-size: 13px;
          color: #606266;
        }
        
        .tree-container {
          padding: 5px;
          min-height: 550px;
          
          .permission-tree {
            width: 100%;
            
            .tree-node-content {
              display: flex;
              align-items: center;
              height: 100%;
              padding: 5px 0;
              
              .category-icon {
                margin-right: 6px;
                font-size: 16px;
                color: #409EFF;
              }
              
              .category-label {
                font-weight: bold;
                color: #303133;
                font-size: 14px;
              }
              
              .category-count {
                margin-left: 8px;
                background-color: #f0f0f0;
                border-radius: 10px;
                min-width: 20px;
                height: 20px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 12px;
                color: #606266;
              }
              
              .node-label {
                font-weight: 500;
                margin-right: 8px;
              }
              
              .node-code {
                font-size: 12px;
                color: #909399;
                margin-right: 8px;
                padding: 2px 6px;
                background-color: #f5f7fa;
                border-radius: 10px;
              }
              
              .info-icon {
                font-size: 14px;
                color: #909399;
                cursor: help;
              }
            }
            
            // 自定义树节点样式
            :deep(.el-tree-node__content) {
              height: auto;
              min-height: 32px;
              
              &:hover {
                background-color: #f5f7fa;
              }
            }
            
            // 选中节点样式
            :deep(.is-checked .el-tree-node__content) {
              background-color: #ecf5ff;
            }
            
            // 展开/折叠图标
            :deep(.el-tree-node__expand-icon) {
              padding: 6px;
            }
            
            // 选择框样式
            :deep(.el-checkbox) {
              margin-right: 8px;
            }
          }
        }
      }
    }
  }
}

// 添加对话框底部边距，确保按钮完全可见
.permission-management-dialog {
  :deep(.el-dialog) {
    display: flex;
    flex-direction: column;
    margin: 0 auto !important;
    max-height: 98vh;
    margin-bottom: 0 !important;
  }
  
  :deep(.el-dialog__header) {
    padding: 15px 20px;
    margin-right: 0;
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
    overflow: hidden;
    flex: 1;
    max-height: calc(98vh - 120px);
  }
  
  :deep(.el-dialog__footer) {
    padding: 15px 20px;
    border-top: 1px solid #f0f0f0;
    margin-top: 0;
    position: relative;
    z-index: 100;
    background-color: #fff;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

.compact-tree-node {
  display: flex;
  align-items: center;
  font-size: 14px;
  line-height: 1.5;
  padding: 4px 0;
  white-space: nowrap;
}

.parent-tree-dropdown {
  position: absolute;
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
  max-height: 250px;
  overflow-y: auto;
}

.tree-search {
  padding: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.tree-search input {
  width: 100%;
  padding: 5px;
  margin-bottom: 10px;
}
</style> 